package com.example.managemyself.ui.tasks;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.managemyself.R;
import com.example.managemyself.data.model.Task;
import com.example.managemyself.viewmodel.TaskViewModel;
import com.example.managemyself.util.DateManager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 任务列表Fragment，用于显示特定类型的任务
 * 支持根据日期筛选任务，确保稳定显示
 */
public class TaskListFragment extends Fragment implements 
        DateManager.DateChangeListener,
        TaskAdapter.OnTaskInteractionListener {
    
    private static final String TAG = "TaskListFragment";
    private static final String ARG_TASK_TYPE = "task_type";
    
    private String taskType;
    private TaskViewModel taskViewModel;
    private RecyclerView recyclerView;
    private TaskAdapter taskAdapter;
    private TextView tvEmpty;
    private DateManager dateManager;
    
    // 数据缓存，避免频繁查询
    private List<Task> cachedTasks = new ArrayList<>();
    private boolean isDataLoaded = false;
    
    public static TaskListFragment newInstance(String taskType) {
        TaskListFragment fragment = new TaskListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_TASK_TYPE, taskType);
        fragment.setArguments(args);
        return fragment;
    }
    
    public void setTaskType(String taskType) {
        this.taskType = taskType;
    }
    
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            taskType = getArguments().getString(ARG_TASK_TYPE);
        }
    }
    
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_task_list, container, false);
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        initViews(view);
        initViewModel();
        setupRecyclerView();
        
        // 确保taskType已正确设置后再观察任务
        if (taskType != null) {
            observeTasks();
        } else {
            Log.e(TAG, "TaskType仍为null，延迟初始化");
            // 延迟100ms后重试，给Fragment时间完成初始化
            view.postDelayed(() -> {
                if (taskType != null) {
                    observeTasks();
                } else {
                    Log.e(TAG, "TaskType最终为null，显示错误状态");
                    showEmptyState("任务类型未设置，请重新进入页面");
                }
            }, 100);
        }
    }
    
    private void initViews(View view) {
        recyclerView = view.findViewById(R.id.recyclerView);
        tvEmpty = view.findViewById(R.id.tvEmpty);
    }
    
    private void initViewModel() {
        if (getActivity() != null) {
            taskViewModel = new ViewModelProvider(requireActivity()).get(TaskViewModel.class);
            dateManager = DateManager.getInstance();
            if (dateManager != null) {
                dateManager.addDateChangeListener(this);
            }
        }
    }
    
    private void setupRecyclerView() {
        if (recyclerView != null) {
            recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
            taskAdapter = new TaskAdapter(taskViewModel);
            taskAdapter.setOnTaskInteractionListener(this);
            recyclerView.setAdapter(taskAdapter);
            recyclerView.setHasFixedSize(true);
        }
    }
    
    private void observeTasks() {
        if (taskViewModel == null || taskType == null) {
            Log.e(TAG, "TaskViewModel或TaskType为空: taskViewModel=" + taskViewModel + ", taskType=" + taskType);
            showEmptyState("任务类型未设置");
            return;
        }
        
        Log.d(TAG, "开始观察任务类型: " + taskType);
        
        try {
            // 移除之前的观察者，避免重复观察
            taskViewModel.getTasksByType(taskType).removeObservers(getViewLifecycleOwner());
            
            taskViewModel.getTasksByType(taskType).observe(getViewLifecycleOwner(), tasks -> {
                Log.d(TAG, "接收到任务数据: " + (tasks != null ? tasks.size() : "null") + " 个任务，类型: " + taskType);
                
                if (tasks != null) {
                    cachedTasks.clear();
                    cachedTasks.addAll(tasks);
                    isDataLoaded = true;
                    
                    Log.d(TAG, "缓存任务数据: " + cachedTasks.size() + " 个任务");
                    
                    // 记录任务详情
                    for (int i = 0; i < Math.min(tasks.size(), 5); i++) {
                        Task task = tasks.get(i);
                        Log.d(TAG, "任务 " + i + ": " + task.getTitle() + ", 类型: " + task.getType() + ", 状态: " + task.getStatus() + ", 完成: " + task.isCompleted());
                    }
                    
                    List<Task> filteredTasks = filterTasksByDate(tasks);
                    Log.d(TAG, "过滤后的任务数量: " + filteredTasks.size());
                    updateUI(filteredTasks);
                } else {
                    Log.w(TAG, "接收到空的任务数据");
                    cachedTasks.clear();
                    isDataLoaded = true;
                    updateUI(new ArrayList<>());
                }
            });
            
            // 同时观察所有任务，用于调试
            taskViewModel.getAllTasks().observe(getViewLifecycleOwner(), allTasks -> {
                Log.d(TAG, "所有任务数量: " + (allTasks != null ? allTasks.size() : "null"));
                if (allTasks != null) {
                    for (Task task : allTasks) {
                        Log.d(TAG, "全部任务: " + task.getTitle() + ", 类型: " + task.getType());
                    }
                }
            });
            
        } catch (Exception e) {
            Log.e(TAG, "观察任务时发生错误", e);
            showEmptyState("加载任务失败: " + e.getMessage());
        }
    }
    
    private void updateUI(List<Task> tasks) {
        if (!isAdded() || getContext() == null) {
            return; // Fragment未附加到Activity，避免崩溃
        }
        
        try {
            if (taskAdapter == null || recyclerView == null || tvEmpty == null) {
                return;
            }
            
            if (!tasks.isEmpty()) {
                taskAdapter.setTasks(tasks);
                recyclerView.setVisibility(View.VISIBLE);
                tvEmpty.setVisibility(View.GONE);
            } else {
                recyclerView.setVisibility(View.GONE);
                tvEmpty.setVisibility(View.VISIBLE);
                
                String dateStr = getSelectedDateString();
                String emptyMessage = String.format("%s 没有未完成的 %s 任务", 
                    dateStr, taskType != null ? taskType : "");
                tvEmpty.setText(emptyMessage);
            }
        } catch (Exception e) {
            showEmptyState("显示任务失败");
        }
    }
    
    private String getSelectedDateString() {
        if (dateManager != null) {
            return dateManager.getFormattedSelectedDate("MM月dd日");
        }
        return "今日";
    }
    
    private void showEmptyState(String message) {
        if (tvEmpty != null && recyclerView != null) {
            recyclerView.setVisibility(View.GONE);
            tvEmpty.setVisibility(View.VISIBLE);
            tvEmpty.setText(message);
        }
    }
    
    private List<Task> filterTasksByDate(List<Task> allTasks) {
        List<Task> filteredTasks = new ArrayList<>();
        
        if (dateManager == null) {
            // 如果日期管理器为空，返回所有未完成的任务
            for (Task task : allTasks) {
                if (!task.isCompleted()) {
                    filteredTasks.add(task);
                }
            }
            return filteredTasks;
        }
        
        Date selectedDate = dateManager.getSelectedDate();
        
        if (selectedDate == null) {
            // 如果没有选择日期，返回所有未完成的任务
            for (Task task : allTasks) {
                if (!task.isCompleted()) {
                    filteredTasks.add(task);
                }
            }
            return filteredTasks;
        }
        
        for (Task task : allTasks) {
            if (!task.isCompleted() && isTaskForSelectedDate(task, selectedDate)) {
                filteredTasks.add(task);
            }
        }
        
        return filteredTasks;
    }
    
    private boolean isTaskForSelectedDate(Task task, Date selectedDate) {
        Date taskDate = task.getDueDate();
        if (taskDate == null) {
            taskDate = task.getCreatedDate();
        }
        
        if (taskDate == null) {
            // 如果任务没有日期，显示在今天
            return isSameDay(new Date(), selectedDate);
        }
        
        return isSameDay(taskDate, selectedDate);
    }
    
    private boolean isSameDay(Date date1, Date date2) {
        if (date1 == null || date2 == null) {
            return false;
        }
        
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        
        return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
               cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
    }
    
    @Override
    public void onDateChanged(Date newDate) {
        if (isDataLoaded && !cachedTasks.isEmpty()) {
            // 使用缓存数据重新过滤，避免重复查询
            List<Task> filteredTasks = filterTasksByDate(cachedTasks);
            updateUI(filteredTasks);
        }
    }
    
    @Override
    public void onTaskClick(Task task) {
        if (taskViewModel != null) {
            taskViewModel.selectTask(task);
        }
    }
    
    @Override
    public void onTaskLongClick(Task task) {
        // TODO: 显示任务操作菜单
    }
    
    @Override
    public void onTaskStatusChanged(Task task, boolean isCompleted) {
        if (taskViewModel != null && task != null) {
            boolean wasCompleted = task.isCompleted();
            task.setCompleted(isCompleted);
            taskViewModel.updateTask(task);
            
            // 如果任务从未完成变为完成，通知日记系统
            if (!wasCompleted && isCompleted) {
                com.example.managemyself.util.TaskCompletionNotifier.getInstance().notifyTaskCompleted(task);
            }
            
            // 立即更新缓存数据
            for (int i = 0; i < cachedTasks.size(); i++) {
                if (cachedTasks.get(i).getId() == task.getId()) {
                    cachedTasks.set(i, task);
                    break;
                }
            }
            
            // 重新过滤显示
            List<Task> filteredTasks = filterTasksByDate(cachedTasks);
            updateUI(filteredTasks);
        }
    }
    
    @Override
    public void onResume() {
        super.onResume();
        // 页面恢复时刷新数据
        if (taskViewModel != null && taskType != null && isDataLoaded) {
            // 使用缓存数据避免频繁查询
            List<Task> filteredTasks = filterTasksByDate(cachedTasks);
            updateUI(filteredTasks);
        }
    }
    
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isResumed() && isDataLoaded) {
            // 当Fragment变为可见时刷新显示
            List<Task> filteredTasks = filterTasksByDate(cachedTasks);
            updateUI(filteredTasks);
        }
    }
    
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && isResumed() && taskType != null) {
            // Fragment从隐藏状态变为可见时，重新观察数据
            Log.d(TAG, "Fragment变为可见，重新初始化: " + taskType);
            if (taskViewModel != null) {
                // 如果有缓存数据，先显示缓存数据
                if (isDataLoaded && !cachedTasks.isEmpty()) {
                    List<Task> filteredTasks = filterTasksByDate(cachedTasks);
                    updateUI(filteredTasks);
                } else {
                    // 没有缓存数据，重新观察
                    observeTasks();
                }
            }
        }
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (dateManager != null) {
            dateManager.removeDateChangeListener(this);
        }
        
        // 清理资源
        cachedTasks.clear();
        isDataLoaded = false;
        taskAdapter = null;
    }
}